package spring.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import ch.qos.logback.classic.Logger;
import custom.data.User;

import utility.Validate;

@Controller
@SessionAttributes("user")
public class LoginController {
	private static Logger logger = (Logger) LoggerFactory.getLogger(LoginController.class);

	@ModelAttribute("user")
	public User getUser() {
		return new User();
	}

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(ModelMap model) {
		// model.addAttribute("content","欢迎进入首页");
		return "index";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(ModelMap model) {

		return new ModelAndView("login", "command", new User());
	}

	@RequestMapping(value = "/login_in", method = RequestMethod.POST)
	public String login_in(@ModelAttribute("user") User user, ModelMap model) {
		if (Validate.checkUser(user.getUserName(), user.getPassword())) {
			model.addAttribute("userName", user.getUserName());
			logger.info("登录用户的用户名为：{}", user.getUserName());
			return "index";

		} else {

			return "login";
		}

	}

	@RequestMapping(value = "/login_out", method = RequestMethod.GET)
	public String login_out(SessionStatus sessionStatus, ModelMap map, ModelMap model) {
		// 销毁session
		User user = (User) map.get("user");
		if (user != null) {
			logger.info("登出用户的用户名为：{}", user.getUserName());
			sessionStatus.setComplete();

		}

		return "index";

	}

}
